package com.library.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class BaseDao {

    //链接数据用库的三个静态变量
    private static final String URL = "jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "025987";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    //加载驱动的静态代码块
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取数据库连接的静态方法
    public static Connection getConnection()  {
        Connection con = null;
        try {
            con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            System.out.println("获取数据库连接成功");
        } catch (SQLException e) {
            System.out.println("获取数据库连接失败");
            e.printStackTrace();  // 输出详细的异常信息
        }
        return con;
    }


    //释放数据库资源的方法
    public static void closeAll(Connection con, java.sql.Statement stmt, java.sql.ResultSet rs) {
        try {
            if (rs!=null) {
                rs.close();
            }
            if (stmt!=null) {
                stmt.close();
            }
            if (con!=null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
